<?php
/**
 * @copyright 2025 银杏WMS
 * @author 银杏WMS
 * @version 1.0
 * @license http://www.hhyx.xyz
 * @developer Lhf
 */

namespace app\admin\controller\yxerp;

use app\common\controller\Backend;
use app\admin\model\yxerp\WarehouseOperation as WarehouseOperationModel;
use app\admin\model\yxerp\WarehouseOperationDetail as WarehouseOperationDetailModel;
use app\admin\model\yxerp\WarehouseOperationType as WarehouseOperationTypeModel;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * 仓库出入库管理
 */
class WarehouseOperation extends Backend
{
    /**
     * 仓库操作模型对象
     * @var WarehouseOperationModel
     */
    protected $model = null;
    
    /**
     * 仓库操作明细模型对象
     * @var WarehouseOperationDetailModel
     */
    protected $detailModel = null;
    
    /**
     * 仓库操作类型模型对象
     * @var WarehouseOperationTypeModel
     */
    protected $typeModel = null;
    
    protected $relationSearch = true;
    
    /**
     * 初始化
     */
    public function initialize()
    {
        parent::initialize();
        $this->model = new WarehouseOperationModel;
        $this->detailModel = new WarehouseOperationDetailModel;
        $this->typeModel = new WarehouseOperationTypeModel;
    }
    
    /**
     * 查看
     */
    public function index()
    {
        // 设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        
        list($where, $sort, $order, $offset, $limit) = $this->buildparams();
        
        $list = $this->model
            ->withJoin(['warehouse' => ['name']])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
            
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        
        return json($result);
    }
    
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if (isset($params['row']) && isset($params['details'])) {
                $mainData = $params['row'];
                $detailsData = $params['details'];
                
                if (empty($detailsData)) {
                    return json(['code' => 0, 'msg' => __('请添加出入库明细')]);
                }
                
                Db::startTrans();
                try {
                    // 获取操作类型
                    $operationType = $this->typeModel->find($mainData['operation_type_id']);
                    if (!$operationType) {
                        throw new \Exception(__('操作类型不存在'));
                    }
                    
                    // 设置操作方向和类型信息
                    $mainData['direction'] = $operationType['direction'];
                    $mainData['operation_type'] = $operationType['code'];
                    $mainData['operation_name'] = $operationType['name'];
                    
                    // 设置操作单号
                    $mainData['operation_no'] = WarehouseOperationModel::generateOperationNo();
                    
                    // 设置创建人信息
                    $mainData['create_user_id'] = $this->auth->id;
                    $mainData['create_user'] = $this->auth->username;
                    
                    // 保存主表数据
                    $operationModel = new WarehouseOperationModel();
                    $operationModel->save($mainData);
                    
                    // 保存明细
                    foreach ($detailsData as $detail) {
                        $detail['operation_id'] = $operationModel->id;
                        $this->detailModel->create($detail);
                    }
                    
                    Db::commit();
                    return json(['code' => 1, 'msg' => __('添加成功')]);
                } catch (\Exception $e) {
                    Db::rollback();
                    return json(['code' => 0, 'msg' => $e->getMessage()]);
                }
            }
            return json(['code' => 0, 'msg' => __('参数不能为空')]);
        }
        return json(['code' => 0, 'msg' => __('非法请求')]);
    }
    
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->find($ids);
        if (!$row) {
            return json(['code' => 0, 'msg' => __('记录不存在')]);
        }
        
        // 获取明细
        $details = $this->detailModel->where('operation_id', $ids)->select();
        
        if ($this->request->isPost()) {
            $params = $this->request->post();
            if (isset($params['row']) && isset($params['details'])) {
                $mainData = $params['row'];
                $detailsData = $params['details'];
                
                if (empty($detailsData)) {
                    return json(['code' => 0, 'msg' => __('请添加出入库明细')]);
                }
                
                // 只有草稿状态可以编辑
                if ($row->status != 1) {
                    return json(['code' => 0, 'msg' => __('只有草稿状态下才能编辑')]);
                }
                
                Db::startTrans();
                try {
                    // 获取操作类型
                    $operationType = $this->typeModel->find($mainData['operation_type_id']);
                    if (!$operationType) {
                        throw new \Exception(__('操作类型不存在'));
                    }
                    
                    // 设置操作方向和类型信息
                    $mainData['direction'] = $operationType['direction'];
                    $mainData['operation_type'] = $operationType['code'];
                    $mainData['operation_name'] = $operationType['name'];
                    
                    // 更新主表数据
                    $row->save($mainData);
                    
                    // 删除原有明细
                    $this->detailModel->where('operation_id', $ids)->delete();
                    
                    // 保存新明细
                    foreach ($detailsData as $detail) {
                        $detail['operation_id'] = $ids;
                        $this->detailModel->create($detail);
                    }
                    
                    Db::commit();
                    return json(['code' => 1, 'msg' => __('更新成功')]);
                } catch (\Exception $e) {
                    Db::rollback();
                    return json(['code' => 0, 'msg' => $e->getMessage()]);
                }
            }
            return json(['code' => 0, 'msg' => __('参数不能为空')]);
        }
        
        return json(['code' => 1, 'data' => [
            'row' => $row,
            'details' => $details
        ]]);
    }
    
    /**
     * 删除
     */
    public function del($ids = '')
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            
            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $item) {
                    // 只有草稿和已取消状态可以删除
                    if ($item->status != 1 && $item->status != 3) {
                        throw new \Exception(__('只有草稿和已取消状态才能删除'));
                    }
                    
                    // 删除明细
                    $this->detailModel->where('operation_id', $item->id)->delete();
                    
                    // 删除主表
                    $count += $item->delete();
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return json(['code' => 0, 'msg' => $e->getMessage()]);
            }
            
            if ($count) {
                return json(['code' => 1, 'msg' => __('删除成功')]);
            } else {
                return json(['code' => 0, 'msg' => __('删除失败')]);
            }
        }
        return json(['code' => 0, 'msg' => __('参数错误')]);
    }
    
    /**
     * 审核
     */
    public function approve($ids = null)
    {
        if (!$ids) {
            return json(['code' => 0, 'msg' => __('参数错误')]);
        }
        
        $row = $this->model->find($ids);
        if (!$row) {
            return json(['code' => 0, 'msg' => __('记录不存在')]);
        }
        
        try {
            $result = $row->approve($ids, $this->auth->id, $this->auth->username);
            if ($result) {
                return json(['code' => 1, 'msg' => __('审核成功')]);
            } else {
                return json(['code' => 0, 'msg' => __('审核失败')]);
            }
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 反审核
     */
    public function unapprove($ids = null)
    {
        if (!$ids) {
            return json(['code' => 0, 'msg' => __('参数错误')]);
        }
        
        $row = $this->model->find($ids);
        if (!$row) {
            return json(['code' => 0, 'msg' => __('记录不存在')]);
        }
        
        try {
            $result = $row->unapprove($ids, $this->auth->id, $this->auth->username);
            if ($result) {
                return json(['code' => 1, 'msg' => __('反审核成功')]);
            } else {
                return json(['code' => 0, 'msg' => __('反审核失败')]);
            }
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 取消
     */
    public function cancel($ids = null)
    {
        if (!$ids) {
            return json(['code' => 0, 'msg' => __('参数错误')]);
        }
        
        $row = $this->model->find($ids);
        if (!$row) {
            return json(['code' => 0, 'msg' => __('记录不存在')]);
        }
        
        try {
            $result = $row->cancel($ids, $this->auth->id, $this->auth->username);
            if ($result) {
                return json(['code' => 1, 'msg' => __('取消成功')]);
            } else {
                return json(['code' => 0, 'msg' => __('取消失败')]);
            }
        } catch (\Exception $e) {
            return json(['code' => 0, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 获取单据详情
     */
    public function detail($ids = null)
    {
        if (!$ids) {
            return json(['code' => 0, 'msg' => __('参数错误')]);
        }
        
        $row = $this->model->find($ids);
        if (!$row) {
            return json(['code' => 0, 'msg' => __('记录不存在')]);
        }
        
        // 获取明细
        $details = $this->detailModel
            ->with(['product', 'unit', 'location'])
            ->where('operation_id', $ids)
            ->select();
        
        return json(['code' => 1, 'data' => [
            'row' => $row,
            'details' => $details
        ]]);
    }
    
    /**
     * 获取操作类型
     */
    public function getOperationTypes()
    {
        $types = $this->typeModel
            ->where('status', 1)
            ->field('id, name, code, direction')
            ->order('id', 'asc')
            ->select();
            
        return json(['code' => 1, 'data' => $types]);
    }
} 